using System;
using System.Collections.Generic;
using System.Net.Http.Json;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using ZechatApp.Messages;
using ZechatApp.Models;
using ZechatApp.Services;
using ZechatApp.Views;

namespace ZechatApp.ViewModels;

public partial class HomePageViewModel : ViewModelBase
{
    [ObservableProperty] private string? _welcomeMessage;
    [ObservableProperty] private List<string> _logMessages = [];
    private readonly HttpServerService _httpServerService;
    private readonly HttpClientService _httpClientService;

    public HomePageViewModel() : this("test")
    {
    }

    public HomePageViewModel(string username)
    {
        _httpServerService = new HttpServerService();
        _httpClientService = App.Services?.GetRequiredService<HttpClientService>() ??
                             throw new Exception("HttpClientService is null");

        WelcomeMessage = $"欢迎, {username}";
    }

    [RelayCommand]
    public async Task StartListeningAsync()
    {
        Console.WriteLine("StartListeningAsync");
        var result = await _httpServerService.StartListenerAsync();
        LogMessages = [..LogMessages, result];
        Console.WriteLine(LogMessages);
    }

    [RelayCommand]
    private async Task GetLoginStatus()
    {
        var response = await _httpClientService.WxPostAsync<WxLoginStatus>(JsonContent.Create(new { Type = 1 }));
        Console.WriteLine($"Login Response: {response}");
    }

    [RelayCommand]
    private async Task GetCurrentUser()
    {
        var response = await _httpClientService.WxPostAsync<WxUser>(JsonContent.Create(new { Type = 3 }));
        Console.WriteLine($"User Response: {response}");
    }

    [RelayCommand]
    private void Logout()
    {
        var msg = new BzMessage(new BzUser());
        WeakReferenceMessenger.Default.Send(msg);
    }
}